package com.xuxueli.applyModules.utils.testhttpclinet;
import com.alibaba.fastjson.JSONObject;
import com.xuxueli.applyModules.exception.ErrorException;
import org.apache.commons.lang3.StringUtils;
import org.apache.http.HttpEntity;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.apache.logging.log4j.util.Strings;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import java.io.IOException;
import java.util.UUID;

/**
 * 测试xml发送是否成功
 */
public class TestHttpPostAndXml {

    public static final Logger log = LoggerFactory.getLogger(TestHttpPostAndXml.class);

    public static void main(String[] args) {
        DcBillStaPushTask task = new DcBillStaPushTask();
        task.setSid(UUID.randomUUID().toString());
        task.setTradeCode("666");
        task.setBillListNo("E666");
        task.setBillStatus("1");
        task.setPreSeqNo("E66620210724");
        task.setEmsListNo("20210724");
        task.setListNo("20210724");
        task.setEmsListNo("20210724");
        task.setRelEntryNo("20210724");
        task.setRelListNo("20210724");
        task.setListIochkptStatus("1");
        task.setListStat("1");
        task.setVrfdedMark("1");
        JSONObject jsonObject = new JSONObject();
        jsonObject.put("Url","http://127.0.0.0:32668");
        jsonObject.put("UrlName","test");
        jsonObject.put("UserName","admin");
        jsonObject.put("PassWord","admin");
        String message = packageMessage(task, jsonObject);
        System.out.println(message);
    }

    /**
     * 状态推送
     * 组装xml报文
     * @return
     */
    public static String packageMessage(DcBillStaPushTask dcBillStaPushTask, JSONObject paramsCode){
        if(paramsCode == null) return null;

        String url = paramsCode.get("Url") == null ? "" : paramsCode.get("Url").toString();
        String urlName = paramsCode.get("UrlName") == null ? "" : paramsCode.get("UrlName").toString();
        String userName = paramsCode.get("UserName") == null ? "" : paramsCode.get("UserName").toString();
        String passWord = paramsCode.get("PassWord") == null ? "" : paramsCode.get("PassWord").toString();
        String preSeqNo = dcBillStaPushTask.getPreSeqNo() == null ? "" : dcBillStaPushTask.getPreSeqNo();
        String tradeCode = dcBillStaPushTask.getTradeCode() == null ? "" : dcBillStaPushTask.getTradeCode();
        String emsListNo = dcBillStaPushTask.getEmsListNo() == null ? "" : dcBillStaPushTask.getEmsListNo();
        String listNo = dcBillStaPushTask.getListNo() == null ? "" : dcBillStaPushTask.getListNo();
        String entryNo = dcBillStaPushTask.getEntryNo() == null ? "" : dcBillStaPushTask.getEntryNo();
        String relEntryNo = dcBillStaPushTask.getRelEntryNo() == null ? "" : dcBillStaPushTask.getRelEntryNo();
        String listIochkptStatus = dcBillStaPushTask.getListIochkptStatus() == null ? "" : dcBillStaPushTask.getListIochkptStatus();
        String relListNo = dcBillStaPushTask.getRelListNo() == null ? "" : dcBillStaPushTask.getRelListNo();
        String listStat = dcBillStaPushTask.getListStat() == null ? "" : dcBillStaPushTask.getListStat();
        String vrfdedMark = dcBillStaPushTask.getVrfdedMark() == null ? "" : dcBillStaPushTask.getVrfdedMark();
        StringBuffer sb = new StringBuffer();
        sb.append("requestData={");
        sb.append("\"DxpSeq\":\""+ preSeqNo + "\",");  //：PRE_SEQ_NO,
        sb.append("\"DealFlag\": \"Y\",");
        sb.append("\"Url\":\""+ url + "\","); //按企业配置
        sb.append("\"UrlName\":\"" + urlName + "\",");
        sb.append("\"SendId\":\"admin\",");
        sb.append("\"ReceiveId\":\""+ tradeCode + "\",");  //：企业编码，TRADE_CODE
        sb.append("\"SendContent\":\"<?xml version=\\\"1.0\\\"?><KtBillHeadRetInfo xmlns:xsi=\\\"http://www.w3.org/2001/XMLSchema-instance\\\" xmlns:xsd=\\\"http://www.w3.org/2001/XMLSchema\\\">");
        sb.append("<UserName>" + userName + "</UserName>"); //按企业配置
        sb.append("<PassWord>" + passWord + "</PassWord>");  //按企业配置
        sb.append("<PoNo>" + emsListNo + "</PoNo>");  //EMS_LIST_NO
        sb.append("<EportListNo>" + listNo + "</EportListNo>"); // list_no
        sb.append("<EntryNo>" + entryNo + "</EntryNo>"); // ENTRY_NO
        sb.append("<RltEntryNo>" + relEntryNo + "</RltEntryNo>"); // REL_ENTRY_NO
        sb.append("<RltInvtNo>" + relListNo + "</RltInvtNo>");  //REL_LIST_NO
        sb.append("<IoChkPt>" + listIochkptStatus + "</IoChkPt>");  // LIST_IOCHKPT_STATUS
        sb.append("<PassDate></PassDate>");  // 空
        sb.append("<ListStat>" + listStat + "</ListStat>"); // ListStat
        sb.append("<VrfdedMarkcd>" + vrfdedMark + "</VrfdedMarkcd>");  // VRFDED_MARK
        sb.append("</KtBillHeadRetInfo>\",");
        sb.append("\"DataType\":\"1\",");
        sb.append("\"MsgType\":\"KT_EMS\"");
        sb.append("}");
        return sb.toString();
    }

    /**
     * 发送POST请求
     * @param url 请求url
     * @param jsonParam 请求数据
     * @return 结果
     */
    public static String doPost(String url, String jsonParam) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String context = StringUtils.EMPTY;
        HttpPost method = new HttpPost(url);
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(10000).setConnectTimeout(20000)
                    .setConnectionRequestTimeout(10000).build();
            method.setConfig(requestConfig);
            if (null != jsonParam) {
                // 解决中文乱码问题
                method.setConfig(requestConfig);
                StringEntity entity = new StringEntity(jsonParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            response = client.execute(method);
            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == 200) {
                HttpEntity resEntity = response.getEntity();
                context = EntityUtils.toString(resEntity, "UTF-8");
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                    method.abort();
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return context;
    }

    /**
     * 发送POST请求
     * @param url 请求url
     * @param jsonParam 请求数据
     * @return 结果
     */
    public static String doPost(String accessToken,String url, String jsonParam) throws Exception {
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String context = StringUtils.EMPTY;
        HttpPost method = new HttpPost(url);
        try {
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(20000).setConnectTimeout(40000)
                    .setConnectionRequestTimeout(20000).build();
            method.setConfig(requestConfig);
            method.addHeader("Authorization", accessToken);
            if (null != jsonParam) {
                // 解决中文乱码问题
                method.setConfig(requestConfig);
                StringEntity entity = new StringEntity(jsonParam, "utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/json");
                method.setEntity(entity);
            }
            log.info(String.format("%s-----%s", "", "accessToken="+accessToken + "准备数据请求"));
            response = client.execute(method);
            log.info(String.format("%s-----%s", "", "accessToken="+accessToken + "请求已发送"));
            HttpEntity resEntity = response.getEntity();
            context = EntityUtils.toString(resEntity, "UTF-8");
            /** 请求发送成功，并得到响应 **/
            if (response.getStatusLine().getStatusCode() == 200) {
                log.info(String.format("%s-----%s", response.getStatusLine().getStatusCode(), "accessToken="+accessToken + "请求发送成功，并获取正确的状态："));
                log.info(String.format("%s-----%s", context, "accessToken="+accessToken + "返回的数据："));
            } else if(response.getStatusLine().getStatusCode() != 200 && !Strings.isBlank(context)){
                throw new ErrorException(500,"发送报文未获取到正确返回，请求返回状态：" + response.getStatusLine().getStatusCode() + "，发送失败，" + context);
            } else if(response.getStatusLine().getStatusCode() != 200 && Strings.isBlank(context)){
                throw new ErrorException(400,"发送报文未获取到正确返回，请求返回状态：" + response.getStatusLine().getStatusCode() + "，发送失败，自动重新发送");
            }
        } catch (Exception e) {
            throw e;
        } finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                    method.abort();
                    client.close();
                } catch (IOException e) {
                }
            }
        }
        return context;
    }

    /**
     * post发送xml报文
     * @param accessToken
     * @param url
     * @param message
     * @return
     * @throws Exception
     */
    public static String doXmlPost(String accessToken,String url, String message) throws Exception{
        CloseableHttpClient client = HttpClients.createDefault();
        CloseableHttpResponse response = null;
        String context = StringUtils.EMPTY;
        HttpPost post = new HttpPost(url);
        try{
            RequestConfig requestConfig = RequestConfig.custom()
                    .setSocketTimeout(40000).setConnectTimeout(40000)
                    .setConnectionRequestTimeout(20000).build();
            post.setConfig(requestConfig);
            post.addHeader("Authorization",accessToken);
            post.addHeader("Accept","text/html, application/xhtml+xml, */*");
            if(StringUtils.isNotBlank(message)){
                StringEntity entity = new StringEntity(message,"utf-8");
                entity.setContentEncoding("UTF-8");
                entity.setContentType("application/x-www-form-urlencoded");
                post.setEntity(entity);
            }
            log.info(String.format("%s-----%s", "", "准备数据请求"));
            response = client.execute(post);
            log.info(String.format("%s-----%s", "", "请求已发送"));
            HttpEntity httpEntity = response.getEntity();
            context = EntityUtils.toString(httpEntity,"UTF-8");
            //** 请求发送成功，并得到响应 **//*
            if (response.getStatusLine().getStatusCode() == 200) {
                log.info(String.format("%s-----%s", response.getStatusLine().getStatusCode(), "accessToken="+accessToken + "请求发送成功，并获取正确的状态："));
                log.info(String.format("%s-----%s", context, "accessToken="+accessToken + "返回的数据："));
            } else if(response.getStatusLine().getStatusCode() != 200 && !Strings.isBlank(context)){
                throw new ErrorException(400,"发送未获取到正确返回，请求返回状态：" + response.getStatusLine().getStatusCode() + "，发送失败，" + context);
            } else if(response.getStatusLine().getStatusCode() != 200 && Strings.isBlank(context)){
                throw new ErrorException(400,"发送未获取到正确返回，请求返回状态：" + response.getStatusLine().getStatusCode() + "，发送失败，自动重新发送");
            }

        }catch (Exception e){
            throw e;
        }finally {
            if (response != null) {
                try {
                    EntityUtils.consume(response.getEntity());
                    response.close();
                    post.abort();
                    client.close();
                } catch (IOException e) {
                    throw e;
                }
            }
        }
        return context;
    }
}
